package com.manli.wechat.utils.wxpayv3.wxsdk;

import com.alibaba.fastjson.JSON;
import com.manli.wechat.utils.wxpayv3.pojo.*;
import com.manli.wechat.utils.wxpayv3.utils.*;
import com.manli.wechat.utils.wxpayv3.wxsdk.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;


@Slf4j
public class WxpayV3Utils {
//    public static String certificateSerialNo = "41438B625799A164EFBD308A43EA9B62C30AF0FC";
//    private static String privateKeyPath = "C:\\Users\\fjc\\Desktop\\1601420795_20200806_cert\\apiclient_key.pem";
//    private static String certificatePath = "C:\\Users\\fjc\\Desktop\\1601420795_20200806_cert\\apiclient_cert.pem";

    //生产
    public static String certificateSerialNo = "41438B625799A164EFBD308A43EA9B62C30AF0FC";
    private static String privateKeyPath = "/root/wxpay/ca/apiclient_key.pem";
    private static String certificatePath = "/root/wxpay/ca/apiclient_cert.pem";

    public static void main(String[] args) throws Exception {
        //图片上传API测试
//        File file = new File("C:\\Users\\fjc\\Desktop\\15994872356986.png");
//        //https://wxpaylogo.qpic.cn/wxpaylogo/PiajxSqBRaEI1qUibGfkJ4NxDdicFlaN1gwvEuQBqafibTJFRVraCMMJHw/0
//        //上面是已经上传的，可以用于代金券测试
//        System.out.println(imgUpload(file,"1601420795"));

        //创建代金券批次测试用例
        //{"create_time":"2020-09-08T11:29:24+08:00","stock_id":"15130247"}创建成功的,可以用于激活发放，但是有时间限制20200908
        //{"create_time":"2020-09-08T16:57:51+08:00","stock_id":"15131259"}
        //{"create_time":"2020-09-08T22:10:41+08:00","stock_id":"15131803"}//20200908
//        CashCouponBatch cashCouponBatch = new CashCouponBatch();
//        cashCouponBatch.setStock_name("漫狸代金券007");
//        cashCouponBatch.setComment("漫狸代金券007_零售");
//        cashCouponBatch.setBelong_merchant("1601420795");
//        cashCouponBatch.setAvailable_begin_time("2020-09-14T12:36:00.000+08:00");
//        cashCouponBatch.setAvailable_end_time("2020-09-15T00:00:00.000+08:00");
//        CashCouponBatchStockUseRule stockRule = new CashCouponBatchStockUseRule();
//        stockRule.setMax_coupons(100L);
//        stockRule.setMax_amount(10000L);
//        stockRule.setMax_amount_by_day(10000L);
//        stockRule.setMax_coupons_per_user(1L);
//        stockRule.setNatural_person_limit(false);
//        stockRule.setPrevent_api_abuse(true);
//        cashCouponBatch.setStock_use_rule(stockRule);
//        CashCouponBatchPatternInfo patternInfo = new CashCouponBatchPatternInfo();
//        patternInfo.setDescription("满2元减1元代金券");
//        patternInfo.setMerchant_logo("https://wxpaylogo.qpic.cn/wxpaylogo/PiajxSqBRaEI1qUibGfkJ4NxDdicFlaN1gwvEuQBqafibTJFRVraCMMJHw/0");
//        patternInfo.setMerchant_name("漫狸科技");
//        patternInfo.setBackground_color("COLOR020");
//        patternInfo.setCoupon_image("https://wxpaylogo.qpic.cn/wxpaylogo/PiajxSqBRaEI1qUibGfkJ4NxDdicFlaN1gwvEuQBqafibTJFRVraCMMJHw/0");
//        cashCouponBatch.setPattern_info(patternInfo);
//        CashCouponBatchCouponUseRule couponUseRule = new CashCouponBatchCouponUseRule();
////        CashCouponBatchCouponUseRuleCouponAvailableTime availableTime = new CashCouponBatchCouponUseRuleCouponAvailableTime();
////
////        couponUseRule.setCoupon_available_time(availableTime);
//        CashCouponBatchCouponUseRuleFixedNormalCoupon normalCoupon = new CashCouponBatchCouponUseRuleFixedNormalCoupon();
//        normalCoupon.setCoupon_amount(100L);
//        normalCoupon.setTransaction_minimum(200L);
//        couponUseRule.setFixed_normal_coupon(normalCoupon);
//        List<String> list = new ArrayList<>();
//        list.add("20200914");
//        couponUseRule.setGoods_tag(list);
//        List<String> list1 = new ArrayList<>();
////        list1.add("1601704787");//子商户号
//        list1.add("1601420795");//子商户号
//        couponUseRule.setAvailable_merchants(list1);
//        cashCouponBatch.setCoupon_use_rule(couponUseRule);
//        cashCouponBatch.setNo_cash(true);
//        cashCouponBatch.setStock_type("NORMAL");
//        cashCouponBatch.setOut_request_no("2020091402");
//        cashCouponBatch(cashCouponBatch,"1601420795");

//        //激活代金券批次测试用例
        //{"start_time":"2020-09-08T11:42:53+08:00","stock_id":"15130247"}激活成功
//        ActivationCouponBatch activationCouponBatch = new ActivationCouponBatch();
//        activationCouponBatch.setStock_creator_mchid("1601420795");
//        activationCouponBatch(activationCouponBatch,"15265849","1601420795");

        //发放代金券测试用例
        //{"coupon_id":"15794127458"}发放成功
        //{"coupon_id":"15792941504"}
        //{"coupon_id":"15794362000"}
        //{"coupon_id":"15813264152"}
//        GrantCoupon grantCoupon = new GrantCoupon();
//        grantCoupon.setStock_id("15143679");
//        grantCoupon.setOut_request_no("202009140102");
//        grantCoupon.setAppid("wx6f56d14c68184b2f");
//        grantCoupon.setStock_creator_mchid("1601420795");
//        grantCoupon(grantCoupon,"oJRQnwvbiRCQGmw6xzMsBCme2ILg","1601420795",certificateSerialNo);

        //暂停代金券批次测试用例
        //{"pause_time":"2020-09-09T14:12:51+08:00","stock_id":"15130247"}
//        StopCoupon stopCoupon = new StopCoupon();
//        stopCoupon.setStock_creator_mchid("1601420795");
//        stopCoupon(stopCoupon,"15130247","1601420795");

        //重启代金券批次
        //{"restart_time":"2020-09-09T14:13:38+08:00","stock_id":"15130247"}
//        StopCoupon stopCoupon = new StopCoupon();
//        stopCoupon.setStock_creator_mchid("1601420795");
//        restartCoupon(stopCoupon,"15130247","1601420795");

        //条件查询批次列表
//        QueryCouponStockStatus stockStatus = new QueryCouponStockStatus();
//        stockStatus.setOffset(0L);
//        stockStatus.setLimit(10L);
//        stockStatus.setStock_creator_mchid("1601420795");
//        queryCouponStockStatus(stockStatus,"1601420795");

        //查询批次详情
//        queryCouponStockInfo("15130247","1601420795","1601420795");

        //查询用户代金券状态用例
        queryUserCoupon("wx6f56d14c68184b2f","oJRQnwpKgeQnlal-xp72MLmGo7Jg","18537053879","1601420795");

        //查询代金券可用商户
//        QueryCouponMerchants merchants = new QueryCouponMerchants();
//        merchants.setOffset(0L);
//        merchants.setLimit(10L);
//        merchants.setStock_creator_mchid("1601420795");
//        queryCouponMerchants(merchants,"15130247","1601420795",certificateSerialNo);

        //查询代金券可用单品
//        QueryCouponMerchants merchants = new QueryCouponMerchants();
//        merchants.setOffset(0L);
//        merchants.setLimit(10L);
//        merchants.setStock_creator_mchid("1601420795");
//        queryCouponItems(merchants,"15130247","1601420795",certificateSerialNo);

        //根据商户号查用户的券
//        QueryCouponByMerchant queryCouponByMerchant = new QueryCouponByMerchant();
//        queryCouponByMerchant.setAppid("wx6f56d14c68184b2f");
//        queryCouponByMerchant.setCreator_mchid("1601420795");
//        queryCouponByMerchant(queryCouponByMerchant,"oJRQnwvbiRCQGmw6xzMsBCme2ILg","1601420795",certificateSerialNo);

        //下载批次核销明细
//        queryCouponUseFlow("15130247","1601420795",certificateSerialNo);

        //下载批次退款明细
//        queryCouponRefundFlow("15130247","1601420795",certificateSerialNo);

//        //设置消息通知地址
//        WeChatPayV3CallBackUrl url = new WeChatPayV3CallBackUrl();
//        url.setMchid("1601420795");
//        url.setNotify_url("http://www.baidu.com");
//        url.setSwitch1(false);
//        callBackUrl(url,"1601420795",certificateSerialNo);
//
//        //全场满额送活动API也已经好了，就是没测试。应该没问题。
//        //创建全场满额送活动API；
//        craeteUniqueThresholdActivity(new UniqueThresholdActivity(),"1601420795",certificateSerialNo);
//        //查询活动详情接口API；
//        queryUniqueThresholdActivity("activityId","1601420795",certificateSerialNo);
//        //查询活动发券商户号API；
//        queryUniqueThresholdActivityMerchants(0L,10l,"activityId", "1601420795",certificateSerialNo);
//        //查询活动指定商品列表API；
//        queryUniqueThresholdActivityGoods(0L,10l,"activityId","1601420795",certificateSerialNo);
//        //终止活动API；
//        stopUniqueThresholdActivity("activityId", "1601420795",certificateSerialNo);
//        //新增活动发券商户号API；
//        addUniqueThresholdActivityMerchant(new AddUniqueThresholdActivityMerchant(),"activityId", "1601420795",certificateSerialNo);
//        //获取支付有礼活动列表API；
//        queryUniqueThresholdActivityList(new QueryUniqueThresholdActivityList(), "1601420795",certificateSerialNo);
//        //删除活动发券商户号API
//        delUniqueThresholdActivity(new DelUniqueThresholdActivityMerchant(),"activityId", "1601420795",certificateSerialNo);
    }

    /**
     * 图片上传API
     * 营销专用-图片上传
     * 通过本接口上传图片后可获得图片url地址。图片url可在微信支付营销相关的API使用，包括商家券、代金券、支付有礼等。
     * @param img
     * @param merchantId    商户号
     * @throws Exception
     */
    public static String imgUpload(File img,String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URI uri = new URI(WxPayUrl.imageUploadUrl);

        String result = null;
        try (FileInputStream s1 = new FileInputStream(img)) {
            String sha256 = DigestUtils.sha256Hex(s1);
            try (InputStream s2 = new FileInputStream(img)) {
                WechatPayUploadHttpPost request = new WechatPayUploadHttpPost.Builder(uri)
                        .withImage(img.getName(), sha256, s2)
                        .build();

                CloseableHttpResponse response1 = httpClient.execute(request);

                try {
                    HttpEntity entity1 = response1.getEntity();
                    result = EntityUtils.toString(entity1);
                    log.info("请求返回：" + result);
                    EntityUtils.consume(entity1);
                }catch (Exception e){
                    throw e;
                } finally {
                    response1.close();
                    httpClient.close();
                }
            }
        }catch (Exception e){
            throw e;
        }

        return result;
    }

    /**
     * 创建代金券批次
     */
    public static String cashCouponBatch(CashCouponBatch jsonBody, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.createCouponStocks);

        String result = null;
        log.info("创建微信代金券请求参数为：" + JSON.toJSONString(jsonBody));
        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 激活代金券批次
     */
    public static String activationCouponBatch(ActivationCouponBatch jsonBody,String stockId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.activationCouponBatch.replace("{stock_id}",stockId));

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 发放代金券
     */
    public static String grantCoupon(GrantCoupon jsonBody,String openid, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.grantCoupon.replace("{openid}",openid));

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 暂停代金券批次
     */
    public static String stopCoupon(StopCoupon jsonBody,String stockId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.stopCoupon.replace("{stock_id}",stockId));

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 重启代金券批次
     */
    public static String restartCoupon(StopCoupon jsonBody,String stockId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.restartCoupon.replace("{stock_id}",stockId));

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 条件查询批次列表
     */
    public static String queryCouponStockStatus(QueryCouponStockStatus body, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponStockStatus);
        uriBuilder.setParameter("offset", body.getOffset().toString());
        uriBuilder.setParameter("limit", body.getLimit().toString());
        uriBuilder.setParameter("stock_creator_mchid", body.getStock_creator_mchid());
        if(!StringUtils.isEmpty(body.getCreate_start_time())){
            uriBuilder.setParameter("create_start_time", body.getCreate_start_time());
        }
        if(!StringUtils.isEmpty(body.getCreate_end_time())){
            uriBuilder.setParameter("create_end_time", body.getCreate_end_time());
        }
        if(!StringUtils.isEmpty(body.getStatus())){
            uriBuilder.setParameter("status", body.getStatus());
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询批次详情
     */
    public static String queryCouponStockInfo(String stockId,String stockCreatorMchid, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponStockInfo.replace("{stock_id}",stockId));
        uriBuilder.setParameter("stock_creator_mchid", stockCreatorMchid);

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询用户代金券状态
     */
    public static String queryUserCoupon(String appid, String openid,String couponId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCoupon.replace("{openid}",openid).replace("{coupon_id}",couponId));
        uriBuilder.setParameter("appid", appid);

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询代金券可用商户
     */
    public static String queryCouponMerchants(QueryCouponMerchants body,String stockId,String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponMerchants.replace("{stock_id}",stockId));
        uriBuilder.setParameter("offset", body.getOffset().toString());
        uriBuilder.setParameter("limit", body.getLimit().toString());
        uriBuilder.setParameter("stock_creator_mchid", body.getStock_creator_mchid());

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询代金券可用单品
     */
    public static String queryCouponItems(QueryCouponMerchants body,String stockId,String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponItems.replace("{stock_id}",stockId));
        uriBuilder.setParameter("offset", body.getOffset().toString());
        uriBuilder.setParameter("limit", body.getLimit().toString());
        uriBuilder.setParameter("stock_creator_mchid", body.getStock_creator_mchid());

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 根据商户号查用户的券
     */
    public static String queryCouponByMerchant(QueryCouponByMerchant body,String openid, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponByMerchant.replace("{openid}",openid));
        uriBuilder.setParameter("appid", body.getAppid());

        if(!StringUtils.isEmpty(body.getStock_id())){
            uriBuilder.setParameter("stock_id", body.getStock_id());
        }
        if(!StringUtils.isEmpty(body.getStatus())){
            uriBuilder.setParameter("status", body.getStatus());
        }
        if(!StringUtils.isEmpty(body.getCreator_mchid())){
            uriBuilder.setParameter("creator_mchid", body.getCreator_mchid());
        }
        if(!StringUtils.isEmpty(body.getSender_mchid())){
            uriBuilder.setParameter("sender_mchid", body.getSender_mchid());
        }
        if(!StringUtils.isEmpty(body.getAvailable_mchid())){
            uriBuilder.setParameter("available_mchid", body.getAvailable_mchid());
        }
        if(body.getOffset() != null){
            uriBuilder.setParameter("offset", body.getOffset().toString());
        }
        if(body.getLimit() != null){
            uriBuilder.setParameter("limit", body.getLimit().toString());
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        log.info("请求地址：" + httpGet.getURI());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 下载批次核销明细
     */
    public static String queryCouponUseFlow(String stockId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponUseFlow.replace("{stock_id}",stockId));

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 下载批次退款明细
     */
    public static String queryCouponRefundFlow(String stockId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryCouponRefundFlow.replace("{stock_id}",stockId));

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 设置消息通知地址
     */
    public static String callBackUrl(WeChatPayV3CallBackUrl jsonBody, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.callBackUrl);

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 创建全场满额送活动API
     */
    public static String craeteUniqueThresholdActivity(UniqueThresholdActivity jsonBody, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.uniqueThresholdActivity);

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询活动详情接口API
     */
    public static String queryUniqueThresholdActivity(String activityId,String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryUniqueThresholdActivity.replace("{activity_id}",activityId));

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询活动发券商户号API
     */
    public static String queryUniqueThresholdActivityMerchants(Long offset,Long limit,String activityId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryUniqueThresholdActivityMerchants.replace("{activity_id}",activityId));
        uriBuilder.setParameter("offset", offset.toString());
        uriBuilder.setParameter("limit", limit.toString());

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 查询活动指定商品列表API
     */
    public static String queryUniqueThresholdActivityGoods(Long offset,Long limit,String activityId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryUniqueThresholdActivityGoods.replace("{activity_id}",activityId));
        uriBuilder.setParameter("offset", offset.toString());
        uriBuilder.setParameter("limit", limit.toString());

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 终止活动API
     */
    public static String stopUniqueThresholdActivity(String activityId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.stopUniqueThresholdActivity.replace("{activity_id}",activityId));

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 新增活动发券商户号API
     */
    public static String addUniqueThresholdActivityMerchant(AddUniqueThresholdActivityMerchant jsonBody,String activityId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.addUniqueThresholdActivityMerchant.replace("{activity_id}",activityId));

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 获取支付有礼活动列表API
     */
    public static String queryUniqueThresholdActivityList(QueryUniqueThresholdActivityList body, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        URIBuilder uriBuilder = new URIBuilder(WxPayUrl.queryUniqueThresholdActivityList);
        uriBuilder.setParameter("offset", body.getOffset().toString());
        uriBuilder.setParameter("limit", body.getLimit().toString());
        if(!StringUtils.isEmpty(body.getActivity_name())){
            uriBuilder.setParameter("activity_name", body.getActivity_name());
        }
        if(!StringUtils.isEmpty(body.getActivity_status())){
            uriBuilder.setParameter("activity_status", body.getActivity_status());
        }
        if(!StringUtils.isEmpty(body.getAward_type())){
            uriBuilder.setParameter("award_type", body.getAward_type());
        }


        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.addHeader("Accept", "application/json");

        CloseableHttpResponse response1 = httpClient.execute(httpGet);
        String result = null;
        try {
            HttpEntity entity1 = response1.getEntity();
            result = EntityUtils.toString(entity1);
            log.info("请求返回：" + result);

            EntityUtils.consume(entity1);
        }catch (Exception e){
            throw e;
        } finally {
            response1.close();
            httpClient.close();
        }

        return result;
    }

    /**
     * 删除活动发券商户号API
     */
    public static String delUniqueThresholdActivity(DelUniqueThresholdActivityMerchant jsonBody,String activityId, String merchantId) throws Exception{
        //证书秘钥初始化
        String content = new String(Files.readAllBytes(Paths.get(privateKeyPath)), "utf-8");
        String content1 = new String(Files.readAllBytes(Paths.get(certificatePath)), "utf-8");

        // 你的商户私钥，缺一不可
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(content.getBytes("utf-8")));
        // 你的微信支付平台证书，缺一不可
        X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(content1.getBytes("utf-8")));

        ArrayList<X509Certificate> listCertificates = new ArrayList<>();
        listCertificates.add(wechatpayCertificate);

        CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, certificateSerialNo, merchantPrivateKey)
                .withWechatpay(listCertificates)
                .build();

        HttpPost httpPost = new HttpPost(WxPayUrl.delUniqueThresholdActivity.replace("{activity_id}",activityId));

        String result = null;

        InputStream stream = new ByteArrayInputStream(JSON.toJSONString(jsonBody).getBytes("utf-8"));
        InputStreamEntity reqEntity = new InputStreamEntity(stream);
        reqEntity.setContentType("application/json");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity2 = response.getEntity();
            result = EntityUtils.toString(entity2);
            log.info("请求返回：" + result);
            EntityUtils.consume(entity2);
        }catch (Exception e){
            throw e;
        } finally {
            response.close();
            httpClient.close();
        }

        return result;
    }

}
